package com.baizhi.controller;

import com.baizhi.common.dto.Product;
import com.baizhi.common.enums.AckCode;
import com.baizhi.common.vo.PageVO;
import com.baizhi.common.vo.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);




    /**
     * 使用最原始的http来访问数据
     * @param userId
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("user/{userId}")
    public R invokeDemo(@PathVariable(value = "userId") int userId) throws JsonProcessingException {
        log.info("user  demo....");

        //模拟一个用户
        Map<String,Object> params=new HashMap<>();
        params.put("userId",userId);
        params.put("userName","小张");


        //调用产品服务中的所有的产品列表信息
        String url="http://localhost:9300/productList?page=1&rows=5";

        R forObject = new RestTemplate().getForObject(url, R.class);

        if(forObject!=null && forObject.getCode()== AckCode.SUCCESS.getCode()){

            Object obj=forObject.getData();
            Map  mp= (Map) obj;

            PageVO pageVo=new PageVO();
            pageVo.setTotal(Long.valueOf(mp.get("total").toString()));

            //取得集合数据
            //序列化成json
            ObjectMapper  objectMapper=new ObjectMapper();
            String productStr=objectMapper.writeValueAsString(mp.get("rows"));
            //把java对象序列化json，再把json反序列化自己要想的对象
            List<Product> productList = objectMapper.readValue(productStr, new TypeReference<List<Product>>() {});
            pageVo.setRows(productList);

            params.put("rows",pageVo);

            return R.okHasData(params);
        }else{
            return forObject;
        }

    }


    /**
     * 服务发现(服务查询)
     * DiscoveryClient接口( spring cloud定义的接口)
     * 1、Eureka
     * 2、nacos   (现在用的)  NacosDiscoveryClient实现类
     * 3、consul
     * 4、zookeeper
     * ..........
     */
    @Autowired
    private DiscoveryClient  discoveryClient;


    /**
     * 使用nacos的服务发现来访问数据
     * @param userId
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/found/user/{userId}")
    public R invokeFoundDemo(@PathVariable(value = "userId") int userId) throws JsonProcessingException {
        log.info("user  demo....");

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("userName", "小张");

        List<ServiceInstance> productserviceList = this.discoveryClient.getInstances("PRODUCTSERVICE");
        if(productserviceList.size()==0){
            R r=R.build(AckCode.FAIL);
            r.setMsg("获取PRODUCTSERVICE列表失败，没有可用的服务");
            return  r;
        }

        //轮询的方法获取服务器访问地址
        String urlPrefix=randomHost(productserviceList);

        //调用产品服务中的所有的产品列表信息
       // String url = "http://localhost:9300/productList";
        String url= urlPrefix+"/productList?page=1&rows=5";

        // Spring框架帮我们封装一个http请求库
        RestTemplate restTemplate = new RestTemplate();
        R forObject = restTemplate.getForObject(url, R.class);
        if (forObject != null && forObject.getCode() == AckCode.SUCCESS.getCode()) {

            Object obj = forObject.getData();
            Map mp = (Map) obj;

            PageVO pageVo = new PageVO();
            pageVo.setTotal(Long.valueOf(mp.get("total").toString()));

            //取得集合数据
            //序列化成json
            ObjectMapper objectMapper = new ObjectMapper();
            String productStr = objectMapper.writeValueAsString(mp.get("rows"));
            //把java对象序列化json，再把json反序列化自己要想的对象
            List<Product> productList = objectMapper.readValue(productStr, new TypeReference<List<Product>>() {
            });
            //打印产品列表信息
            for (Product p : productList) {
                System.out.println(p.toString());
            }
            pageVo.setRows(productList);

            params.put("rows", pageVo);

            return R.okHasData(params);
        } else {
            return forObject;
        }
    }


    /**
     * 随机
     * @return
     */
    public String randomHost(List<ServiceInstance>  serviceInstanceList){
        //生成随机数 只能在0-hosts.size()
        int i = new Random().nextInt(serviceInstanceList.size());
        //nacos实现了ServiceInstance接口   DefaultServiceInstance
        ServiceInstance serviceInstance = serviceInstanceList.get(i);
        //String uri = String.format("http://%s:%s", scheme, instance.getHost(), 	instance.getPort())
        return  serviceInstance.getUri().toString();
    }

    /**
     * 定义一个整数
     */
    private AtomicInteger  atomicInteger=new AtomicInteger(0);
    /**
     * 轮询
     * @param serviceInstanceList
     * @return
     */
    public String roundBalacer(List<ServiceInstance>  serviceInstanceList){
        int number=  Math.abs(atomicInteger.getAndIncrement());
        int index=number % serviceInstanceList.size();
        ServiceInstance serviceInstance = serviceInstanceList.get(index);
        String url=serviceInstance.getUri().toString();
        return url;
    }




}
